package com.zzx.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @Author: zzx
 * @Date: 2025/7/18 21:56
 * 微信二维码生成工具类
 */
@Component
public class QRCodeGenerator {


    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private static final String QR_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.secret}")
    private String secret;


    public byte[] generateAndSaveQRCode(String scene) {
        String accessToken = getAccessToken();
        if (accessToken == null || accessToken.isEmpty()) {
            System.out.println("Failed to obtain access token.");
            return null;
        }

        byte[] qrCodeBytes = generateQRCode(accessToken, scene);
        if (qrCodeBytes == null || qrCodeBytes.length == 0) {
            System.out.println("Failed to generate QR code.");
            return null;
        }
        return qrCodeBytes;
    }

    private String getAccessToken() {
        String url = String.format(ACCESS_TOKEN_URL, appId, secret);
        JSONObject jsonObject = JSONUtil.parseObj(HttpUtil.createGet(url).execute().body());
        if (jsonObject.containsKey("errcode")) {
            System.err.println("Error obtaining access token: " + jsonObject.getStr("errmsg"));
            return null;
        }
        return jsonObject.getStr("access_token");
    }

    private byte[] generateQRCode(String accessToken, String scene) {
        String url = String.format(QR_CODE_URL, accessToken);
//        String jsonBody = "{\"scene\":\"" + scene + "\",\"page\":\"pages/index/index\",\"width\":430}";
        JSONObject jsonBody = new JSONObject();
        jsonBody.set("scene", scene);
        jsonBody.set("page", "pages/index/index");
        jsonBody.set("width", 430);
        jsonBody.set("auto_color", true); // 可选：自动配色
        jsonBody.set("is_hyaline", true); // 可选：透明背景
        HttpRequest request = HttpUtil.createPost(url)
                .body(jsonBody.toString())
                .header("Content-Type", "application/json");

//        return request.execute().bodyBytes();
        // 获取响应体并检查是否为错误信息
        String responseBody = request.execute().body();
        if (responseBody.startsWith("{")) {
            JSONObject error = JSONUtil.parseObj(responseBody);
            if (error.containsKey("errcode")) {
                int errcode = error.getInt("errcode");
                if (errcode != 0) {
                    System.err.println("生成二维码失败：" + error);
                    return null;
                }
            }
        }
        return responseBody.getBytes(StandardCharsets.UTF_8);
    }

//    private void saveQRCodeToDatabase(String scene, byte[] qrCodeBytes) {
//        QRCode qrCode = new QRCode();
//        qrCode.setScene(scene);
//        qrCode.setQrCodeImage(qrCodeBytes);
//
//        qrCodeRepository.save(qrCode);
//    }

}
